import rclpy
from rclpy.node import Node
import requests
from example_interfaces.msg import String
import time
from queue import Queue

class NovelPubNode(Node):
    def __init__(self,node_name):
        super().__init__(node_name)
        self.get_logger().info(f'{node_name},启动！')
        self.novels_queue_ = Queue() # 创建队列，用于存储小说内容
        # 创建话题发布者，发布小说内容
        self.novel_publisher_ = self.create_publisher(String,'novel',10)
        # 创建定时器，定时发布小说内容
        self.timer_ = self.create_timer(5, self.timer_publish_novel_callback) # 5s发布一次小说内容

    def download_novel(self,url):
        self.get_logger().info('下载小说！')
        response = requests.get(url)
        response.encoding = 'utf-8'
        self.get_logger().info('小说下载完成！')
        for line in response.text.splitlines():
            self.novels_queue_.put(line) # 将小说内容放入队列中

    def timer_publish_novel_callback(self):
        if self.novels_queue_.empty():
            self.get_logger().info('小说队列为空！')
            pass
        
        msg = String() # 创建消息
        msg.data = self.novels_queue_.get() # 获取小说内容
        self.novel_publisher_.publish(msg) # 发布小说内容
        self.get_logger().info(f'小说内容：{msg.data}') # 打印小说内容



def main():
    rclpy.init()
    node = NovelPubNode('novel_pub_node')
    node.download_novel('http://127.0.0.1:8000/1.txt')
    rclpy.spin(node)
    rclpy.shutdown()